package com.example.todo.controller;

import com.example.todo.model.Todo;
import com.example.todo.model.TaskStatus;
import com.example.todo.repository.TodoRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/todos")
public class TodoController {

    private static final Logger logger = LoggerFactory.getLogger(TodoController.class);

    @Autowired
    private TodoRepository todoRepository;

    @GetMapping
    public List<Todo> getAllTodos() {
        logger.info("获取所有待办事项");
        return todoRepository.findAll();
    }

    @PostMapping
    public Todo createTodo(@RequestBody Todo todo) {
        logger.info("创建新的待办事项: {}", todo.getText());
        return todoRepository.save(todo);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Todo> updateTodo(@PathVariable Long id, @RequestBody Todo todoDetails) {
        logger.info("更新待办事项，ID: {}", id);
        Todo todo = todoRepository.findById(id)
                .orElseThrow(() -> {
                    logger.error("未找到待办事项，ID: {}", id);
                    return new RuntimeException("Todo not found with id " + id);
                });

        todo.setText(todoDetails.getText());
        todo.setCompleted(todoDetails.isCompleted());
        todo.setCompletedAt(todoDetails.getCompletedAt());
        todo.setStatus(todoDetails.getStatus());

        Todo updatedTodo = todoRepository.save(todo);
        logger.info("待办事项更新成功，ID: {}", id);
        return ResponseEntity.ok(updatedTodo);
    }

    @PutMapping("/{id}/status")
    public ResponseEntity<Todo> updateTodoStatus(@PathVariable Long id, @RequestBody TaskStatus status) {
        logger.info("更新待办事项状态，ID: {}, 新状态: {}", id, status);
        Todo todo = todoRepository.findById(id)
                .orElseThrow(() -> {
                    logger.error("未找到待办事项，ID: {}", id);
                    return new RuntimeException("Todo not found with id " + id);
                });

        todo.setStatus(status);
        if (status == TaskStatus.DONE) {
            todo.setCompleted(true);
            todo.setCompletedAt(java.time.LocalDateTime.now());
        } else {
            todo.setCompleted(false);
            todo.setCompletedAt(null);
        }

        Todo updatedTodo = todoRepository.save(todo);
        logger.info("待办事项状态更新成功，ID: {}", id);
        return ResponseEntity.ok(updatedTodo);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteTodo(@PathVariable Long id) {
        logger.info("删除待办事项，ID: {}", id);
        Todo todo = todoRepository.findById(id)
                .orElseThrow(() -> {
                    logger.error("未找到待办事项，ID: {}", id);
                    return new RuntimeException("Todo not found with id " + id);
                });

        todoRepository.delete(todo);
        logger.info("待办事项删除成功，ID: {}", id);
        return ResponseEntity.ok().build();
    }
}
